package com.ruoyi.framework.web.service

import com.ruoyi.common.core.domain.entity.SysUser
import com.ruoyi.common.core.domain.model.LoginUser
import com.ruoyi.common.enums.UserStatus
import com.ruoyi.common.exception.ServiceException
import com.ruoyi.common.utils.MessageUtils.message
import com.ruoyi.common.utils.MyStringUtils
import com.ruoyi.system.service.ISysUserService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.stereotype.Service

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
class UserDetailsServiceImpl : UserDetailsService {
    @Autowired
    private lateinit var userService: ISysUserService

    @Autowired
    private lateinit var passwordService: SysPasswordService

    @Autowired
    private lateinit var permissionService: SysPermissionService
    @Throws(UsernameNotFoundException::class)
    override fun loadUserByUsername(username: String): UserDetails {
        val user = userService.selectUserByUserName(username)
        if (MyStringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", username)
            throw ServiceException(message("user.not.exists"))
        } else if (UserStatus.DELETED.code == user!!.delFlag) {
            log.info("登录用户：{} 已被删除.", username)
            throw ServiceException(message("user.password.delete"))
        } else if (UserStatus.DISABLE.code == user.status) {
            log.info("登录用户：{} 已被停用.", username)
            throw ServiceException(message("user.blocked"))
        }
        passwordService.validate(user)
        return createLoginUser(user)
    }

    private fun createLoginUser(user: SysUser?): UserDetails {
        return LoginUser(user!!.userId, user.deptId, user, permissionService.getMenuPermission(user))
    }

    companion object {
        private val log = LoggerFactory.getLogger(UserDetailsServiceImpl::class.java)
    }
}
